<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class CartController extends Controller
{
    public function index()
    {
    	$mem_id=session('member_id');
    	$mycarts=DB::table('cart')->leftJoin('product','product.product_id','=','cart.pro_id')->where('mem_id','=',$mem_id)->get();
    	$mycartc=DB::table('cart')->leftJoin('product','product.product_id','=','cart.pro_id')->where('mem_id','=',$mem_id)->count();
    	//var_dump($mycarts);
    	
    	return view('home/main/cart',['mycarts'=>$mycarts,'mycartc'=>$mycartc]);
    }

    public function add(Request $request)
    {
    	$data = $request -> except('_token');
    	$pdata = DB::table('product') -> where('product_id',$data['proid']) -> select('pre_pro_code','keyword')->first();

        $attr=DB::table('pro_attr')->where('pro_id',$data['proid'])->where('cosir_id',$data['cosirid'])->select('attr_stocknum')->first();
        //return response()->json($attr->attr_stocknum);
        //return response()->json($data['buynum']);
        if($attr->attr_stocknum<$data['buynum'])
        {
            $str='该型号已没货';
            return response()->json($str);
            
        }

    	$procode = $pdata->pre_pro_code.$data['sufprocode'];
    	$prokeyword=$pdata->keyword.$data['keyword'];
    	$mem_id = session('member_id');
    	$cartid=DB::table('cart') -> insertGetId(['mem_id'=>$mem_id,'pro_id'=>$data['proid'],'cosir_id'=>$data['cosirid'],'pro_code'=>$procode,'buynum'=>$data['buynum'],'atime'=>time(),'pro_keyword'=>$prokeyword]);
        return response() -> json($cartid);
        
    	
    }
    public function del(Request $request)
    {
    	//var_dump($request->all());
    	//var_dump($request->cart_id);
    	if(is_array($request->cart_id))
    	{
    		$del_cart_arr=$request->cart_id;
    	}else{
    		$del_cart_arr=array();
    		$del_cart_arr[]=$request->cart_id;
    		//var_dump($del_cart_arr);
    	}
    	DB::table('cart')->whereIn('cart_id',$del_cart_arr)->delete();
    	return back();
    }

    //更新商品数量
	public function update(Request $request)
	{
		$data = $request -> except('_token');
		$buynum = $data['buynum'];
		$id = $data['id'];
		$res = DB::table('cart') -> where('cart_id',$id) -> update(['buynum'=>$buynum]);
		return response() -> json($res);
	}

}
